package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"shop/conf"
	"sync"
)

var (
	DB   *gorm.DB
	err  error
	once sync.Once
)

func MySqlInit() {
	once.Do(func() {
		appconf := conf.AppConf.MySqlConfig
		dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True", appconf.User, appconf.Password, appconf.Host, appconf.Port, appconf.Database)
		DB, err = gorm.Open(mysql.Open(dsn))
		if err != nil {
			fmt.Println("数据库连接失败")
			return
		} else {
			fmt.Println("数据库连接成功")
		}
		err = DB.AutoMigrate(&Shop{})
		if err != nil {
			fmt.Println("迁移失败")
			return
		}
		fmt.Println("迁移成功")
	})
}
